package de.slothsoft.commons.swing.editorview;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolBar;

import de.slothsoft.commons.res.CommonImages;
import de.slothsoft.commons.res.CommonMessages;

public class PartTab extends JPanel {

	private static final long serialVersionUID = 1L;

	private EditorViewPanel parent;
	private JLabel titleLabel;
	private Part part;

	public PartTab(EditorViewPanel parent) {
		this.parent = parent;
		createLayout();
	}

	private void createLayout() {
		setOpaque(false);
		setLayout(new BorderLayout());
		this.titleLabel = new JLabel();
		this.titleLabel.setOpaque(false);
		add(this.titleLabel, BorderLayout.CENTER);
		add(createCloseButton(), BorderLayout.EAST);
	}

	protected JComponent createCloseButton() {
		JButton button = new JButton(CommonImages.get(CommonImages.MENU_CLOSE));
		button.setToolTipText(CommonMessages.getString("Dialog.close"));
		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				closePart();
			}
		});
		button.setBackground(null);
		button.setBorderPainted(false);
		button.setBorder(null);
		button.setRolloverEnabled(true);
		button.setRolloverIcon(CommonImages
				.get(CommonImages.MENU_CLOSE_ROLLOVER));

		JToolBar bar = new JToolBar();
		bar.add(button);
		bar.setFloatable(false);
		bar.setOpaque(false);
		return bar;
	}

	public void updateControlsFromPart(Part part) {
		this.part = part;
		this.titleLabel.setText(this.part.getTitle());
		this.titleLabel.setIcon(this.part.getIcon());
		this.titleLabel.setToolTipText(this.part.getTip());
	}

	protected void closePart() {
		if (this.part instanceof Editor) {
			this.parent.closeEditor((Editor<?>) this.part);
		} else {
			this.parent.closeView((View) this.part);
		}
	}
}
